package ltd.hxya.novel.book.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import ltd.hxya.novel.book.entity.Book;
import ltd.hxya.novel.book.mapper.BookMapper;
import ltd.hxya.novel.book.service.IBookService;
import ltd.hxya.novel.book.service.impl.BookServiceImpl;
import ltd.hxya.novel.common.constant.redis.RedisConstant;
import ltd.hxya.novel.common.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Configuration
public class BookConfig {

    @Autowired
    private IBookService bookService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private BookMapper bookMapper;

    @Value("${sys.visit.count.time}")
    private Integer syncInterval;

    //分别从数据库中查询出最受欢迎的分类
    @PostConstruct
    public void bookType(){
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(5);
        executor.scheduleWithFixedDelay(()->{
            //对数据库中的所有小说进行分类
            try {
                bookService.bookRecommend();
            }catch (Exception exception){
                exception.printStackTrace();
            }
        },0,1, TimeUnit.HOURS);
    }

    @PostConstruct
    public void syncVisitCount(){
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(5);
        executor.scheduleWithFixedDelay(()->{
            try {
                List<String> keyList = redisUtils.getByPattern(RedisConstant.BOOK_VISIT_COUNT);
                //批量从redis中查询信息
                Map<String,Integer> map = new HashMap<>();
                List<Book> collect = keyList.stream().map(key -> {
                    Book book = new Book();
                    String[] split = key.split(":");
                    book.setId(split[split.length-1]);
                    String value = redisUtils.get(key);
                    book.setVisitCount(Long.valueOf(value));
                    return book;
                }).collect(Collectors.toList());
                //保存到数据库中
                if (!CollectionUtils.isEmpty(collect)){
                    bookMapper.changeVisitCount(collect);
                    //删除键
                    redisUtils.deleteBatch(keyList);
                }
            }catch (Exception exception){
                exception.printStackTrace();
            }
        },0,syncInterval,TimeUnit.MINUTES);
    }
}
